package com.funo.logic.controller;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.json.JSONUtil;
import com.funo.logic.model.RequestParameter;
import com.funo.logic.response.HandleResult;
import com.funo.logic.service.CompilationInParameterService;
import com.google.common.collect.Lists;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * 参数请求controller
 * @since 2024年7月17日16:20:16
 * @author cms
 */
@RestController
@RequestMapping("requestParameter")
public class RequestParameterController extends AbstractController{

    @Autowired
    private StringRedisTemplate stringRedisTemplate;
    @Autowired
    private CompilationInParameterService compilationInParameterService;

    /**
     * 保持或者更新请求参数合集
     * @param list 请求参数集合
     * @return HandleResult
     */
    @PostMapping("saveOrUpdate")
    public HandleResult saveOrUpdate(@RequestBody List<RequestParameter> list, @RequestParam String arrangeId) {
        if (CollectionUtil.isEmpty(list)) {
            return HandleResult.fail("参数不能为空");
        }
        String key = getCacheKey(list.get(0).getBelongNodeId());
        stringRedisTemplate.delete(key);
        stringRedisTemplate.opsForValue().set(key, JSONUtil.toJsonStr(list));
        compilationInParameterService.resetRequestParameter(arrangeId, list);
        return HandleResult.success();
    }

    @GetMapping("getByBelongNodeId")
    public HandleResult getByBelongNodeId(String belongNodeId) {
        String key = getCacheKey(belongNodeId);
        String value = stringRedisTemplate.opsForValue().get(key);
        if (StringUtils.isBlank(value)) {
            return HandleResult.success(Lists.newArrayList());
        }
        return HandleResult.success(JSONUtil.parseArray(value).toList(RequestParameter.class));
    }

    @Override
    public String getCachePrefix() {
        return "requestParameter:";
    }
}
